package com.dj.mingkong.portal.biz.service.music.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dj.mingkong.common.constant.RedisConstants;
import com.dj.mingkong.common.infrastructure.eo.database.music.AlbumEo;
import com.dj.mingkong.common.infrastructure.eo.database.music.AlbumVisitEo;
import com.dj.mingkong.common.microservice.UserContext;
import com.dj.mingkong.common.util.AssertUtils;
import com.dj.mingkong.portal.biz.controller.music.vo.request.AlbumVisitAddVo;
import com.dj.mingkong.portal.biz.controller.music.vo.request.AlbumVisitCancelVo;
import com.dj.mingkong.portal.biz.controller.music.vo.request.AlbumVisitQueryVo;
import com.dj.mingkong.portal.biz.controller.music.vo.response.AlbumVisitVo;
import com.dj.mingkong.portal.biz.core.base.context.UserContextHolder;
import com.dj.mingkong.portal.biz.repository.database.music.AlbumRepository;
import com.dj.mingkong.portal.biz.repository.database.music.AlbumVisitRepository;
import com.dj.mingkong.portal.biz.service.music.AlbumVisitService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.SecureRandom;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 专辑访客服务实现
 *
 * @author zenglonghui
 * @date: 2022/8/23 10:24
 */
@Slf4j
@Service("albumVisitService")
public class AlbumVisitServiceImpl implements AlbumVisitService {
    @Resource
    private AlbumVisitRepository albumVisitRepository;
    @Resource
    private AlbumRepository albumRepository;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private UserContextHolder userContextHolder;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(AlbumVisitAddVo addVo) {
        final AlbumEo albumEo = albumRepository.getById(addVo.getAlbumId());
        AssertUtils.isNotNull(albumEo, "albumId invalid");
        //添加人气
        addPopularity(addVo);
        userContextHolder.getCurrentUserOpt().ifPresent(userInfoContext -> {
            final String key = RedisConstants.VISIT_ALBUM
                    .concat(userInfoContext.getId().toString())
                    .concat(RedisConstants.KEY_SPLIT)
                    .concat(addVo.getAlbumId().toString());
            if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) {
                saveAlbumVisit(key, userInfoContext.getId(), albumEo);
            }
        });
    }

    @Override
    public Page<AlbumVisitVo> pageByVo(AlbumVisitQueryVo queryVo) {
        return albumVisitRepository.getMapper().listPage(Page.of(queryVo.getPage(), queryVo.getPageSize()), queryVo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancel(AlbumVisitCancelVo cancelVo) {
        final AlbumEo albumEo = albumRepository.getById(cancelVo.getAlbumId());
        AssertUtils.isNotNull(albumEo, "albumId invalid");
        final Optional<AlbumVisitEo> optional = albumVisitRepository
                .oneOptByUserIdAndAlbumId(UserContext.getUserId(), cancelVo.getAlbumId());
        optional.ifPresent(albumVisitEo -> {
            albumVisitRepository.deleteById(albumVisitEo.getId());
            albumRepository.updateById(albumEo.setVisitCount(albumEo.getVisitCount() - 1));
        });
    }

    private void saveAlbumVisit(String key, Long userId, AlbumEo albumEo) {
        final Optional<AlbumVisitEo> optional = albumVisitRepository.oneOptByUserIdAndAlbumId(userId, albumEo.getId());
        optional.ifPresentOrElse(albumVisitEo -> {
            log.info("更新访客信息 userId:{}, albumId:{}", userId, albumEo.getId());
            albumVisitRepository.updateById(albumVisitEo);
            redisTemplate.opsForValue().set(key, RedisConstants.VISIT_ALBUM, 1, TimeUnit.MINUTES);
        }, () -> {
            log.info("保存访客信息 userId:{}, albumId:{}", userId, albumEo.getId());
            final AlbumVisitEo visitEo = AlbumVisitEo.builder().userId(userId)
                    .albumId(albumEo.getId()).build();
            albumVisitRepository.save(visitEo);
            redisTemplate.opsForValue().set(key, RedisConstants.VISIT_ALBUM, 1, TimeUnit.MINUTES);
            albumRepository.updateById(albumEo.setVisitCount(albumEo.getVisitCount() + 1));
        });
    }

    private void addPopularity(AlbumVisitAddVo addVo) {
        final var rand = new SecureRandom();
        final long num = rand.nextLong(10) + 1;
        final Long increment = redisTemplate.boundHashOps(RedisConstants.POPULARITY_ALBUM)
                .increment(addVo.getAlbumId(), num);
        log.info("添加专辑人气 id :{}, 点击数： {}", addVo.getAlbumId(), increment);
    }
}
